#include "thumbnailbar.h"

#include "reporteditor_global.h"
#include "imagelabel.h"

#include <QClipboard>
#include <QApplication>
#include <QMimeData>

ThumbnailBar::ThumbnailBar(QWidget *parent) :
    currLabel(0),
    QWidget(parent)
{
    setFocusPolicy(Qt::StrongFocus);
    layout = new QBoxLayout(QBoxLayout::TopToBottom, this);
    layout->setContentsMargins(6, 6, 6, 6);
    layout->addStretch();
    layout->setAlignment(Qt::AlignCenter);
    connect(qApp->clipboard(), SIGNAL(dataChanged()), this, SLOT(onClipboardImageReady()));
}

ThumbnailBar::~ThumbnailBar()
{
    clear();
}

void ThumbnailBar::loadImage(const QString &png)
{
    insertImage(QPixmap(png));
}

void ThumbnailBar::onClipboardImageReady()
{
    QClipboard *c = qApp->clipboard();
    const QMimeData *m = c->mimeData();
    if (m->hasImage()) {
        QPixmap p = qvariant_cast<QPixmap>(m->imageData());
        insertImage(p);
        //c->clear();
    }
}

void ThumbnailBar::insertImage(const QPixmap &pixmap)
{
    if (pixmap.isNull()) return;

    ImageLabel *l = new ImageLabel;
    l->setPixmap(pixmap);
    layout->insertWidget(labels.size(), l);
    connect(l, SIGNAL(labelPressed(ImageLabel*)), this, SLOT(onLabelPressed(ImageLabel*)));
    connect(l, SIGNAL(labelActived(ImageLabel*)), this, SLOT(onLabelActived(ImageLabel*)));
    labels += l;
    if (currLabel == 0) {
        currLabel = l;
        currLabel->setActive(true);
    }
}

QPixmap ThumbnailBar::getCurrentPixmap() const
{
    return currLabel?currLabel->pixmap():QPixmap();
}

void ThumbnailBar::onLabelPressed(ImageLabel *label)
{
    if (currLabel) currLabel->setActive(true);
    currLabel = label;
}

void ThumbnailBar::onLabelActived(ImageLabel *label)
{
    if (currLabel && currLabel != label)
        currLabel->setActive(false);
    currLabel = label;
    if (label) emit imageActived(label->pixmap());
}

void ThumbnailBar::clear()
{
    foreach (ImageLabel *l, labels) {
        layout->removeWidget(l);
        l->deleteLater();
    }
    labels.clear();
    currLabel = 0;
}

QSize ThumbnailBar::sizeHint() const
{
    QMargins margin = layout->contentsMargins();
    int width = IMAGE_LABEL_SIZE;
    int height = IMAGE_LABEL_SIZE*labels.size();
    if (labels.size() > 1)
        height += (labels.size()-1)*layout->spacing();

    switch (layout->direction()) {
    case QBoxLayout::TopToBottom:
    case QBoxLayout::BottomToTop:
        return QSize(width + margin.left() + margin.right(),
                     height + margin.top() + margin.bottom());
        break;
    case QBoxLayout::LeftToRight:
    case QBoxLayout::RightToLeft:
        return QSize(width + margin.top() + margin.bottom(),
                     height + margin.left() + margin.right());
        break;
    default:
        return QSize();
    }
}
